<?php

    class UserController extends Zend_Controller_Action{

        private $_view = null;
        private $_config= null;
        public  $_session= null;
        public $_users;

        public function init() {
            $this->_users = new Model_DbTables_User_User();
            /* Initialize action controller here */
            //bezieht viewinstanz
            $this->_view = $this->_helper->layout->getView();

            //Config aus der application.ini auslesen
            $bootstrap = $this->getInvokeArg('bootstrap');
            $config = $bootstrap->getOptions();

            $this->_config = $config['appConfig'];

            //SESSION
            $this->_session = new Zend_Session_Namespace('oncut');
        }

        public function indexAction(){
            $form = new Form_User_User();
            $form->addSubForm(new Form_Confirm(), 'confirm');

            //wenn cancle button gedrueckt
            if($this->_hasParam('cancle')){
                $this->_redirect('index');
            }elseif($this->_hasParam('submit')){
                if($form->isValid($this->_getAllParams())){
                    $newUserID = $this->_users->addUser($this->_getAllParams());
                    //send registration-mail to user
                    $mail = new Model_Email();
                    $mail->sendMail($this->_users->getUser($newUserID));
                }
            }

            $this->view->form = $form;
        }

        public function indexcompleteAction(){

        }

        /**
         * Gespeicherte User Projekte anzeigen
         */
        public function myprojectsAction(){

            //init Tabbles
            $dbUser = new Model_DbTables_User_Userproject();

            if( $this->_getParam('del') ){
                $dbUser->deleteUserProjects( Zend_Auth::getInstance()->getIdentity()->fe_user_nid, $this->_getParam('del'));
            }

            //Projekte vom User selektieren
            $rsProjects = $dbUser->getUserProjects(Zend_Auth::getInstance()->getIdentity()->fe_user_nid);



            $arrayDetail = array();
            $i = 0 ;
            $hour   = 0;
            $minute = 0;
            $second = 0;
            $date   = 0;
            foreach($rsProjects AS $row){

                $jsonArray = json_decode($rsProjects[0]['fe_userprojects_json']);


                foreach($jsonArray AS $detail){
                    //print_r($detail->vThumb);
                    if($i == 0){
                       $arrayDetail[$i]['image'] =  $detail->vThumb;
                    }

                    $time  = explode(":", $detail->vDuration);

                    $hour   += $time[0];
                    $minute += $time[1];
                    $second += $time[2];
                }

                $date = mktime($hour,$minute,$second);
                $arrayDetail[$i]['vDuration'] =  date("H:i:s", $date);
                $i ++;
            }



            //Wertingkeiten an den View übergeben
            $this->view->projects       = $rsProjects;
            $this->view->projectsDetail = $arrayDetail;


        }



        public function exportAction(){

        }

        /**
         *
         */
        public function editAction(){
            $form = new Form_User_User();
            $form->addSubForm(new Form_Confirm(), 'confirm');

            //fill form with user data from authstorage
            $identity = Zend_Auth::getInstance()->getStorage()->read();
            $form->populate((array)$identity);

            if($this->_hasParam('submit')){
                //add id to paramlist
                $this->_setParam('id', $identity->fe_user_nid);

                if($form->isValid($this->_getAllParams())){
                    $valid = true;
                    if($this->_getParam('fe_user_email') !== $identity->fe_user_email){
                        if($this->_users->emailReserved($this->_getParam('fe_user_email'))){
                            $form->fe_user_email->clearErrorMessages();
                            $form->fe_user_email->addError('emailReserved');
                            $valid = false;
                        }else{
                            //change authstoragedata if email was changed
                            $identity->fe_user_email = $this->_getParam('fe_user_email');
                            $storage = new Zend_Session_Namespace($this->_request->getModuleName());
                            $storage->fe_user_mail = $this->_getParam('fe_user_email');
                        }
                    }

                    if($valid){
                        $this->_users->editUser($this->_getAllParams());
                    }
                }
            }elseif($this->_hasParam('cancle')){
                $this->_redirect('index');
            }

            $this->view->form      = $form;
        }

        public function loginAction() { //identiteat wird erstellt

            $this->view->error = false;
        	if (Zend_Auth::getInstance()->hasIdentity ()) { // wenn schon eingeloggt, dann fehlermeldung
                $this->_redirect('index');
            } else {
                $this->view->errorMessage = false;
                $request = $this->getRequest();
                $form = new Form_User_Login();
                $this->view->form = $form;
                if ($request->isPost() && $this->_hasParam('login')) {
                    if ($form->isValid($this->_request->getPost())) {
                        $authAdapter = $this->getAuthAdapter();

                        $username = $form->getValue ( 'username' );
                        $password = md5($form->getValue ( 'password' ));//passwort muss verschluesselt werden
                        $authAdapter->setIdentity ( $username )->setCredential ( $password ); //eingegebenes Passwort und Benutzername wird dem AuthAdapter uebergheben

                        $auth = Zend_Auth::getInstance ();

                        //je nach modul wird eine anderes namespace verwendet!
                        $auth->setStorage(new Zend_Auth_Storage_Session($this->_request->getModuleName()));

                        $result = $auth->authenticate($authAdapter);//authAdapter durchsucht die UserTabelle nach username und password
                        if ($result->isValid ()) {
                            $identity = $authAdapter->getResultRowObject ();//identitaet wird ausgegeben
                            if(!$identity->deleted){
                                $auth->getStorage ()->write ( $identity );
                                $this->_redirect ( 'index' );
                            }else{
                                $form->setAttrib('class', 'error');
                                $this->view->errorMessage = "Ihre Zugangsdaten wurden gesperrt. Bitte wenden Sie sich an den Administrator.";
                                Zend_Auth::getInstance ()->clearIdentity ();
                            }
                        } else {
                            $this->view->errorMessage = "Sie haben eine falsche E-Mail-Adresse oder </br> ein falsches Passwort eingegeben.
                                                         Bitte &uuml;berpr&uuml;fen Sie Ihre Eingaben.";
                            $form->setAttrib('class', 'error');
                        }
                    }else{
                        $form->setAttrib('class', 'error');
                    }
                }
            }
        }


        public function logoutAction() {//hier wird die rolle geloescht
    		if(Zend_Auth::getInstance ()->hasIdentity ()){
            	Zend_Auth::getInstance ()->clearIdentity ();
            }
            $this->_redirect('index');
        }

        private function getAuthAdapter() {
            $authAdapter = new Zend_Auth_Adapter_DbTable ( Zend_Db_Table::getDefaultAdapter () );
            $authAdapter->setTableName('fe_user')->setIdentityColumn('fe_user_email')->setCredentialColumn('fe_user_password');

            return $authAdapter;
        }
    }
